// ********************保险类型********************
var express = require('express');
var router = express.Router();
const {insurancesModel}=require('../model/insurancesModel')

// 新增
router.post('/addInsurances',async(req,res)=>{
  try{
    const result=await insurancesModel.create(req.body)
    if(result){
      res.send({
        code:1,
        message:'保险种类增加成功'
      })
    }
  }catch(err){
     res.send({
       code:0,
       message:'保险种类增加失败'
     })
  }
})

// 分页查询
router.get('/getInsurancesByPage',async(req,res)=>{
  const {currentPage=1,pageSize=5}=req.query
  console.log('当前页',currentPage);
  console.log('每页的记录数',pageSize);
  let start=(currentPage-1)*pageSize
  let rows=await insurancesModel.find().populate("typesId").skip(start).limit(pageSize) //按分页查询
  let total=await insurancesModel.countDocuments() //获取总记录数
  let pages=total%pageSize==0?parseInt(total/pageSize):parseInt(total/pageSize)+1
  res.send({
      code:1,
      data:{
          total,
          pages,
          rows,
          currentPage
      }
  })
})

// 删除
router.put('/delInsurances',async(req,res)=>{
  console.log('=========删除保险==========='); 
  try{
    const {modifiedCount}=await insurancesModel.updateOne({_id:req.body._id},req.body)
    if(modifiedCount){
       res.send({
           code:1,
           message:'保险类型删除成功'
       })
    }else{
       res.send({
           code:0,
           message:'保险类型删除失败'
       })
    }
  }catch(err){
    res.send({
       code:-1,
       message:"异常出现"
    })
  }
})

// 修改
router.put('/modifyInsurances',async(req,res)=>{
  console.log('=========修改保险==========='); 
  try{
    const {modifiedCount}=await insurancesModel.updateOne({_id:req.body._id},req.body)
    if(modifiedCount){
       res.send({
           code:1,
           message:'保险类型修改成功'
       })
    }else{
       res.send({
           code:0,
           message:'保险类型修改失败'
       })
    }
  }catch(err){
    res.send({
       code:-1,
       message:"异常出现"
    })
  }
})

module.exports = router;
